class Admin::GioHangController < ApplicationController
  include ApplicationHelper
  def index
    @trang = (params[:page].present? && params[:page].to_i > 1 ?  params[:page] : 1).to_i
    @ngon_ngu = I18n.locale.to_s

    if ['da_xu_ly'].include?(params[:loc])
      query = GioHang.where(:da_xac_nhan => true, :da_xu_ly => true)
    else
      query = GioHang.where(:da_xac_nhan => true, :da_xu_ly => false)
    end
    
    @so_luong_mot_trang = CauHinh.lay_gia_tri_hoac_khoi_tao('admin_so_luong_tren_trang', 20).gia_tri.to_i

    @don_hangs = query.paginate(
      :order => :updated_at.desc,
      :per_page => @so_luong_mot_trang,
      :page => @trang
    )
    @co_trang_sau = !query.paginate(
      :order => :updated_at.desc,
      :per_page => @so_luong_mot_trang,
      :page => @trang + 1
    ).empty?
    @co_trang_truoc = @trang > 1
    @index_dau_tien = (@trang - 1) * @so_luong_mot_trang
  end
  
  def cap_nhat
    @gio_hang = GioHang.find(params[:uid]) || not_found
    @nhan_viens = NguoiDung.where(:is_nhan_vien => true, :dang_kich_hoat => true).sort(:ten_hien_thi.asc).all
    @nguoi_dung = nguoi_dung_hien_tai
    @ngon_ngu = I18n.locale.to_s
    if params[:commit].present?
      if params[:dia_chi_nhan_hang].blank?
        flash.now[:loi] = t 'dia_chi_nhan_hang_khong_dc_de_trong'
      else
        nhan_vien = NguoiDung.find(params[:nhan_vien_id])
        if nhan_vien.present?
          @gio_hang.nhan_vien_giao_hang = nhan_vien
          @gio_hang.nhan_vien_xu_ly = @nguoi_dung
          @gio_hang.da_xu_ly = true
          @gio_hang.save
        else
          @gio_hang.nhan_vien_giao_hang = nil
          @gio_hang.nhan_vien_xu_ly = @nguoi_dung
          @gio_hang.da_xu_ly = false
          @gio_hang.save
        end
        flash.now[:thanh_cong] = t 'don_hang_da_duoc_xu_ly'
      end
    end
  end

end
